package com.xingkeduo.service.cms.marketing.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample.Criteria;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponExample;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCard;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCardWithBLOBs;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCoupon;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCouponBag;
import com.xingkeduo.model.po.TMarketingUseHistory;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingReceiveHistoryResponseVo;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.WeekUtil;
import com.xingkeduo.util.tool.ResponseMessage;

@Service(value = "marketingCouponBagReceiveService")
public class MarketingCouponBagReceiveServiceImpl extends MarketingReceiveServiceImpl {
	Logger logger = LoggerFactory.getLogger(MarketingCouponBagReceiveServiceImpl.class);
	@Override
	public ResponseMessage getUserMarketingReceiveList(MarketingReceiveHistoryParam couponReceiveHistoryExample) {
		TMarketingReceiveHistoryCouponBagExample example = new TMarketingReceiveHistoryCouponBagExample();
		Criteria criteria = example.createCriteria();
		// 领券编号
		if (StringUtils.isNotBlank(couponReceiveHistoryExample.getReceiveNo())) {
			criteria.andReceiveNoEqualTo(couponReceiveHistoryExample.getReceiveNo());
		}
		// 券类型
		if (couponReceiveHistoryExample.getCouponBagType()!=null) {
			criteria.andCouponBagTypeEqualTo(couponReceiveHistoryExample.getCouponBagType());
		}
//		if (couponReceiveHistoryExample.getMarketingType() != null && couponReceiveHistoryExample.getMarketingType()
//				.intValue() != MarketingTypeEnum.COUPON_BAG.getCode()) {
//			criteria.andMarketingTypeEqualTo(couponReceiveHistoryExample.getMarketingType());
//		}
		if (couponReceiveHistoryExample.getMarketingType() != null && couponReceiveHistoryExample.getMarketingType()
				.intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			criteria.andMarketingBagIdIsNotNull();
		}
		// 券Id,券名称
		if (StringUtils.isNumeric(couponReceiveHistoryExample.getMarketingInfo())) {
			if (couponReceiveHistoryExample.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
				criteria.andMarketingBagIdEqualTo(Long.valueOf(couponReceiveHistoryExample.getMarketingInfo()));
			} else {
				criteria.andMarketingIdEqualTo(Long.valueOf(couponReceiveHistoryExample.getMarketingInfo()));
			}
		} else if (StringUtils.isNotBlank(couponReceiveHistoryExample.getMarketingInfo())) {
			criteria.andMarketingNameLike("%" + couponReceiveHistoryExample.getMarketingInfo() + "%");
		}
		// 领取方式
		if (couponReceiveHistoryExample.getSendType() != null) {
			criteria.andSendTypeEqualTo(couponReceiveHistoryExample.getSendType());
		}
		// 领取门店
		if (couponReceiveHistoryExample.getStoreId() != null) {
			criteria.andStoreIdEqualTo(couponReceiveHistoryExample.getStoreId());
		}
		//兑换码
		if (StringUtils.isNotBlank(couponReceiveHistoryExample.getRedeemCode())) {
			criteria.andRedeemCodeEqualTo(couponReceiveHistoryExample.getRedeemCode());
		}
		if (StringUtils.isNotBlank(couponReceiveHistoryExample.getReceiveStartTime())) {
			criteria.andCreateTimeGreaterThanOrEqualTo(
					DateUtils.parseDate(couponReceiveHistoryExample.getReceiveStartTime()));
		}
		if (StringUtils.isNotBlank(couponReceiveHistoryExample.getReceiveEndTime())) {
			//如2017-01-01 ，理论上应该包含当天，所以查询日期需要加1天
			Date endDate = DateUtils.addSomeDays(DateUtils.parseDate(couponReceiveHistoryExample.getReceiveEndTime()), 1);
			criteria.andCreateTimeLessThanOrEqualTo(endDate);
		}
		if (StringUtils.isNotBlank(couponReceiveHistoryExample.getUserInfo())) {
			List<Long> userIdList = userService.queryUserIdsByMobileOrId(couponReceiveHistoryExample.getUserInfo());
			criteria.andUserIdIn(userIdList);
		}
		example.setOrderByClause(" id desc");
		PageHelper.startPage(couponReceiveHistoryExample.getPageNum(), couponReceiveHistoryExample.getPageSize());
		List<TMarketingReceiveHistoryCouponBag> historyList = tMarketingReceiveHistoryCouponBagMapper
				.selectByExample(example);
		PageInfo<TMarketingReceiveHistoryCouponBag> page = new PageInfo<>(historyList);
		PageInfo<MarketingReceiveHistoryResponseVo> pageReturn = new PageInfo<>();
		BeanUtils.copyProperties(page, pageReturn);
		List<MarketingReceiveHistoryResponseVo> returnList = historyList.stream().map(this::buildMarketingReceiveHistoryResponse)
                .collect(Collectors.toList());
		pageReturn.setList(returnList);
		return ResponseMessage.ok(pageReturn);
	}
	@Override
	public ResponseMessage getUserMarketingUseDetail(Long receiveHistoryId, Integer marketingType) {
		// 领取信息
		TMarketingReceiveHistory history = selectMarketingReceiveHistoryByPrimaryKey(receiveHistoryId, marketingType);
		MarketingReceiveHistoryResponseVo vo = new MarketingReceiveHistoryResponseVo();
		BeanUtils.copyProperties(history, vo);
		// 券，卡信息
		TMarketing tMarketing = tMarketingCouponBagMapper.selectByPrimaryKey(history.getMarketingBagId());
		if(tMarketing ==null) {
			return ResponseMessage.ok(vo);
		}
		MarketingResponseVo marketingResponse = new MarketingResponseVo();
		BeanUtils.copyProperties(tMarketing, marketingResponse);
		StringBuffer daysInfo = new StringBuffer();
		if (StringUtils.isNotBlank(tMarketing.getWeekHourIds()) && (!"0".equals(tMarketing.getWeekHourIds()))) {
			// 赋值活动时间
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(tMarketing.getId())
					.andActivityTypeEqualTo(tMarketing.getMarketingType()).andStatusEqualTo(Constant.STATUS_YES);
			List<ActivityDaysResponseVo> activityDaysResponseList = new ArrayList<ActivityDaysResponseVo>();
			List<TActivityDays> activityDaysList = tActivityDaysMapper.selectByExample(example);

			int size = activityDaysList.size();
			for (int i = 0; i < size; i++) {
				TActivityDays activityDays = activityDaysList.get(i);
				ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(activityDays, activityDaysResponseVo);
				activityDaysResponseList.add(activityDaysResponseVo);
				String days = activityDays.getDayids();
				if (days.startsWith(",")) {
					days = days.substring(1, days.length());
				}
				if (days.endsWith(",")) {
					days = days.substring(0, days.length() - 1);
				}
				daysInfo.append(WeekUtil.convertWeek(days)).append(", ")
				.append(DateUtils.formatDate(activityDays.getStartTime(), DateUtils.TIME_FORMAT)).append("~")
				.append(DateUtils.formatDate(activityDays.getEndTime(), DateUtils.TIME_FORMAT)).append("; ");
			}
			marketingResponse.setActivityDays(activityDaysResponseList);
		} else {
			// daysInfo.append("日期: 周一至周日; 时间: 0:00 ~ 24:00;");
			daysInfo.append("无限制;");
		}
		marketingResponse.setDayMemo(daysInfo.toString());
		vo.settMarketing(marketingResponse);
		// 领取信息
		Map<String,String> userInfo = userService.queryOnlyUserInfosByUserId(history.getUserId());
		if(MapUtils.isNotEmpty(userInfo)) {
			vo.setUserInfo(history.getUserId()+"_"+userInfo.get("name"));
			vo.setUserMobile(userInfo.get("phone"));
		}
		return ResponseMessage.ok(vo);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage auditUserMarketing(Long couponBagReceiveHistoryId, Integer marketingType, Integer status) {
		Integer exchangeStatus = MarketingReceiveStatusEnum.AVAILABLE.getCode();
		if (status.intValue() == MarketingReceiveStatusEnum.AVAILABLE.getCode()) {
			exchangeStatus = MarketingReceiveStatusEnum.DISABLED.getCode();
		} else if (status.intValue() == MarketingReceiveStatusEnum.DISABLED.getCode()) {
			exchangeStatus = MarketingReceiveStatusEnum.AVAILABLE.getCode();
		}
		TMarketingReceiveHistoryCouponBag couponBag = tMarketingReceiveHistoryCouponBagMapper
				.selectByPrimaryKey(couponBagReceiveHistoryId);
		if (couponBag == null) {
			return ResponseMessage.error("查询优惠包信息为空", 500);
		}
		// 更改用户券状态
		TMarketingReceiveHistoryCoupon couponHistory = new TMarketingReceiveHistoryCoupon();
		couponHistory.setStatus(status);
		TMarketingReceiveHistoryCouponExample couponExample = new TMarketingReceiveHistoryCouponExample();
		couponExample.createCriteria().andMarketingBagReceiveHistoryIdEqualTo(couponBagReceiveHistoryId)
		        .andUseEndTimeGreaterThan(new Date())
				.andStatusEqualTo(exchangeStatus);
		tMarketingReceiveHistoryCouponMapper.updateByExampleSelective(couponHistory, couponExample);
		// 更改用户卡状态
		TMarketingReceiveHistoryCardWithBLOBs cardHistory = new TMarketingReceiveHistoryCardWithBLOBs();
		cardHistory.setStatus(status);
		TMarketingReceiveHistoryCardExample cardExample = new TMarketingReceiveHistoryCardExample();
		cardExample.createCriteria().andMarketingBagReceiveHistoryIdEqualTo(couponBagReceiveHistoryId)
				.andUseEndTimeGreaterThan(new Date())
				.andStatusEqualTo(exchangeStatus);
		tMarketingReceiveHistoryCardMapper.updateByExampleSelective(cardHistory, cardExample);
		// 更新券包状态
		TMarketingReceiveHistoryCouponBag couponBagHistory = new TMarketingReceiveHistoryCouponBag();
		couponBagHistory.setId(couponBagReceiveHistoryId);
		couponBagHistory.setStatus(status);
		tMarketingReceiveHistoryCouponBagMapper.updateByPrimaryKeySelective(couponBagHistory);
		return ResponseMessage.ok("处理成功");
	}

	@Override
	public ResponseMessage getMarketingBagUseHisory(Long marketingReceiveHistoryId, Integer marketingType) {
		TMarketingReceiveHistory history = selectMarketingReceiveHistoryByPrimaryKey(marketingReceiveHistoryId,
				marketingType);
		if (history == null || history.getMarketingBagId() == null) {
			return ResponseMessage.error("查询领取信息失败", 500);
		}
		List<TMarketingReceiveHistory> tMarketingReceiveHistoryList = getUserMarketingBagReceiveHistoryList(history);
		List<MarketingReceiveHistoryResponseVo> marketingReceiveHistoryResponseVoList = new ArrayList<>();
		for (TMarketingReceiveHistory tMarketingReceiveHistory : tMarketingReceiveHistoryList) {
			MarketingReceiveHistoryResponseVo responseVo = new MarketingReceiveHistoryResponseVo();
			BeanUtils.copyProperties(tMarketingReceiveHistory, responseVo);
			if(tMarketingReceiveHistory.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
				List<TMarketingUseHistory> tMarketingUseHistoryList = selectMarketingUseHistory(tMarketingReceiveHistory);
				responseVo.setMarketingUseHistory(tMarketingUseHistoryList);
			}
			TMarketing marketing = selectByPrimaryKey(tMarketingReceiveHistory.getMarketingId(),
					tMarketingReceiveHistory.getMarketingType());
			responseVo.setStoreNames(marketing.getStoreNames());
			marketingReceiveHistoryResponseVoList.add(responseVo);
		}
		return ResponseMessage.ok(marketingReceiveHistoryResponseVoList);
	}

	private List<TMarketingReceiveHistory> getUserMarketingBagReceiveHistoryList(TMarketingReceiveHistory history) {
		List<TMarketingReceiveHistory> returnList = new ArrayList<>();
		TMarketingReceiveHistoryCouponExample tMarketingReceiveHistoryExample = new TMarketingReceiveHistoryCouponExample();
		tMarketingReceiveHistoryExample.createCriteria().andMarketingBagReceiveHistoryIdEqualTo(
						(history.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()
								? history.getId()
								: history.getMarketingBagReceiveHistoryId()));
		List<TMarketingReceiveHistoryCoupon> tMarketingReceiveHistoryCouponList = tMarketingReceiveHistoryCouponMapper
				.selectByExample(tMarketingReceiveHistoryExample);
		if (!CollectionUtils.isEmpty(tMarketingReceiveHistoryCouponList)) {
			returnList.addAll(tMarketingReceiveHistoryCouponList);
		}
		TMarketingReceiveHistoryCardExample tMarketingReceiveHistoryCardExample = new TMarketingReceiveHistoryCardExample();
		tMarketingReceiveHistoryCardExample.createCriteria().andMarketingBagReceiveHistoryIdEqualTo(
						(history.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()
								? history.getId()
								: history.getMarketingBagReceiveHistoryId()));
		List<TMarketingReceiveHistoryCard> tMarketingReceiveHistoryCardList = tMarketingReceiveHistoryCardMapper
				.selectByExample(tMarketingReceiveHistoryCardExample);
		if (!CollectionUtils.isEmpty(tMarketingReceiveHistoryCardList)) {
			returnList.addAll(tMarketingReceiveHistoryCardList);
		}
		return returnList;
	}
}
